package com.zjy.service.impl;

import com.zjy.bean.*;
import com.zjy.dao.*;
import com.zjy.dto.GoodsDTO;
import com.zjy.dto.GoodsParam;
import com.zjy.dto.GoodsResponse;
import com.zjy.dto.ListResponse;
import com.zjy.service.GoodsService;
import com.zjy.utils.ObjectUtils;
import com.zjy.utils.UUIDUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * Created by Administrator on 2019/4/12.
 */
@Service
public class GoodsServiceImpl implements GoodsService{
    @Resource
    private GoodsMapper goodsMapper;
    @Resource
    private GoodsDetailMapper goodsDetailMapper;
    @Resource
    private GoodsPhotoMapper goodsPhotoMapper;
    @Resource
    private UserCollectionMapper userCollectionMapper;
    @Resource
    private ArticleTagRelationMapper articleTagRelationMapper;
    @Resource
    private ArticleTagMapper articleTagMapper;
    @Resource
    private GoodsCategoryMapper goodsCategoryMapper;
    @Resource
    private GoodsBrandMapper goodsBrandMapper;

    /**
     * 新增商品
     * @param goods
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public String addGoods(GoodsDTO goods) {
        //获取商品分类id和品牌id
        String categoryId = goods.getCategoryId();
        String brandId = goods.getBrandId();
        GoodsCategory  gc = goodsCategoryMapper.selectGoodsCategoryById(categoryId);
        GoodsBrand gb = goodsBrandMapper.selectGoodsBrandById(brandId);
        if(!ObjectUtils.isNullOrEmpty(gc)){
            goods.setCategory(gc.getCategoryName());
        }
        if(!ObjectUtils.isNullOrEmpty(gb)){
            goods.setBrand(gb.getBrandName());
        }
        String id = UUIDUtils.getUUID();
        goods.setId(id);
        goodsMapper.insertSelective(goods);
        //获取商品标签数组，加入文章标签关系表（商品标签关系和文章标签关系共用一张表）
        List<String> tagIdList = goods.getTagIdList();
        if(!ObjectUtils.isNullOrEmpty(tagIdList)){
            for (String s : tagIdList) {
                ArticleTagRelation articleTagRelation = new ArticleTagRelation();
                articleTagRelation.setId(UUIDUtils.getUUID());
                articleTagRelation.setArticleId(id);//将上面生成的商品id传入
                articleTagRelation.setTagId(s);
                articleTagRelationMapper.insertSelective(articleTagRelation);
            }
        }
        return id;
    }

    /**
     * 根据Id软删除商品
     * @param goodsId
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int deleteGoodsById(String goodsId) {
        int count = goodsMapper.deleteGoodsById(goodsId); //根据商品id软删除商品表
        goodsDetailMapper.deleteByGoodsId(goodsId);  //根据商品id软删除商品详情表
        goodsPhotoMapper.deleteByGoodsId(goodsId);  //根据商品id软删除商品图片
        userCollectionMapper.deleteByGoodsId(goodsId);//根据商品id软删除用户收藏表
        articleTagRelationMapper.deleteArticleTagRelation(goodsId);//根据商品id软删除商品标签关系表（文章标签关系表）
        return count;
    }

    /**
     * 根据Id更新商品
     * @param goods
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updateGoodsById(GoodsDTO goods) {
        //获取商品分类id和品牌id
        String categoryId = goods.getCategoryId();
        String brandId = goods.getBrandId();
        GoodsCategory  gc = goodsCategoryMapper.selectGoodsCategoryById(categoryId);
        GoodsBrand gb = goodsBrandMapper.selectGoodsBrandById(brandId);
        if(!ObjectUtils.isNullOrEmpty(gc)){
            goods.setCategory(gc.getCategoryName());
        }
        if(!ObjectUtils.isNullOrEmpty(gb)){
            goods.setBrand(gb.getBrandName());
        }
        //获取商品标签，更新商品标签关系表（文章标签关系表）
        List<String> tagIdList = goods.getTagIdList();
        articleTagRelationMapper.deleteArticleTagRelation(goods.getId());  //软删除文章标签关系表
        //将用户选择的商品标签插入文章标签关系表
        if(!ObjectUtils.isNullOrEmpty(tagIdList) && tagIdList.size() > 0){
            for (String s : tagIdList) {
                ArticleTagRelation articleTagRelation = new ArticleTagRelation();
                articleTagRelation.setId(UUIDUtils.getUUID());
                articleTagRelation.setArticleId(goods.getId());
                articleTagRelation.setTagId(s);
                articleTagRelationMapper.insertSelective(articleTagRelation);
            }
        }

        return goodsMapper.updateByPrimaryKeySelective(goods);
    }

    /**
     * 根据Id查询商品
     * @param goodsId
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Goods selectGoodsById(String userId,String goodsId) {
        Goods goods = goodsMapper.selectGoodsById(goodsId);
        if(goods != null){
            //增加浏览数
            goods.setReadNum(goods.getReadNum() + 1);
            goodsMapper.updateByPrimaryKeySelective(goods);

            //设置是否收藏标志位
            UserCollection u = userCollectionMapper.selectByTwoId(userId,goodsId);
            if(u != null && u.getDelFlag() == 0){
                goods.setIsCollection(1);
            }else {
                goods.setIsCollection(0);
            }
        }
        return goods;
    }

    /**
     * 查询已上架商品列表
     * @param param
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public ListResponse selectGoodsList(GoodsParam param) {
        ListResponse response = new ListResponse();
        String userId = param.getUserId();
        double pageSize = param.getPageSize(); //获取页面大小
        int totalCount = goodsMapper.getGoodsCount(param);  //获取总条数
        int totalPage = 0;
        if(pageSize > 0){
            totalPage = (int)Math.ceil((double)totalCount/pageSize); //计算总页数，结果向上取整
        }
        List<Goods> goodsList = goodsMapper.selectGoodsList(param);
        List<GoodsResponse> goodsResponseList = new ArrayList<GoodsResponse>();
        if(goodsList != null){
            for (Goods goods : goodsList) {
                GoodsResponse goodsResponse = new GoodsResponse();
                List<ArticleTag> goodsTagList = articleTagMapper.selectArticleTagByArticleId(goods.getId());
                //设置是否收藏标志位
                String targetId = goods.getId();
                UserCollection u = userCollectionMapper.selectByTwoId(userId,targetId);
                if(u != null && u.getDelFlag() == 0){
                    goods.setIsCollection(1);
                }else {
                    goods.setIsCollection(0);
                }
                goodsResponse.setGoods(goods);
                goodsResponse.setGoodsTagList(goodsTagList);
                goodsResponseList.add(goodsResponse);
            }
        }
        response.setData(goodsResponseList);
        response.setPageNum(param.getPageNum());
        response.setPageSize(param.getPageSize());
        response.setTotalCount(totalCount);
        response.setTotalPage(totalPage);
        return response;
    }

    /**
     * 获取已上架商品总条数
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int getGoodsCount(GoodsParam param) {
        return goodsMapper.getGoodsCount(param);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public HashMap<String, Object> getGoodsData() {
        HashMap<String,Object> map = new HashMap<>();
        int totalCount = 0;
        int isSaleCount = 0;
        int lowStockCount = 0;
        totalCount = goodsMapper.getGoodsCount(new GoodsParam()); //参数没具体值，查询出所有商品数
        GoodsParam goodsParam = new GoodsParam();
        goodsParam.setIsSale(1);
        isSaleCount = goodsMapper.getGoodsCount(goodsParam);
        lowStockCount = goodsMapper.getLowStockCount();

        map.put("totalCount",totalCount);
        map.put("isSaleCount",isSaleCount);
        map.put("lowStockCount",lowStockCount);
        return map;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int addGoodsCollection(UserCollection userCollection) {
        //查询是否存在userId和targetId的关系，若不存在则插入一条，存在则修改del_flag
        UserCollection u = userCollectionMapper.selectByTwoId(userCollection.getUserId(),userCollection.getTargetId());
        if(u == null){
            u = new UserCollection();
            u.setId(UUIDUtils.getUUID());
            u.setTargetType(0);
            u.setUserId(userCollection.getUserId());
            u.setTargetId(userCollection.getTargetId());
            userCollectionMapper.insertSelective(u);
        }else if(u != null && u.getDelFlag() == 1){
            u.setDelFlag(0);
            userCollectionMapper.updateByPrimaryKeySelective(u);
        }
        //修改商品的收藏数+1
        String goodsId = userCollection.getTargetId();
        return goodsMapper.updateCollectionNum(goodsId,1);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int cancelGoodsCollection(UserCollection userCollection) {
        //软删除用户收藏表
        userCollectionMapper.deleteByTwoId(userCollection.getUserId(),userCollection.getTargetId());
        //修改商品的收藏数-1
        String goodsId = userCollection.getTargetId();
        return goodsMapper.updateCollectionNum(goodsId,-1);
    }

    /**
     * 查询用户收藏列表
     * @param param
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public ListResponse getGoodsCollection(GoodsParam param) {
        ListResponse response = new ListResponse();
        double pageSize = param.getPageSize(); //获取页面大小
        int totalCount = goodsMapper.getGoodsCollectionCount(param);  //获取总条数
        int totalPage = 0;
        if(pageSize > 0){
            totalPage = (int)Math.ceil((double)totalCount/pageSize); //计算总页数，结果向上取整
        }
        List<Goods> goodsList = goodsMapper.getGoodsCollection(param);
        List<GoodsResponse> goodsResponseList = new ArrayList<GoodsResponse>();
        if(goodsList != null){
            for (Goods goods : goodsList) {
                GoodsResponse goodsResponse = new GoodsResponse();
                List<ArticleTag> goodsTagList = articleTagMapper.selectArticleTagByArticleId(goods.getId());
                goodsResponse.setGoods(goods);
                goodsResponse.setGoodsTagList(goodsTagList);
                goodsResponseList.add(goodsResponse);
            }
        }
        response.setData(goodsResponseList);
        response.setPageNum(param.getPageNum());
        response.setPageSize(param.getPageSize());
        response.setTotalCount(totalCount);
        response.setTotalPage(totalPage);
        return response;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int deleteGoodsCollection(HashMap<String, Object> param) {
        String userId = (String) param.get("userId");
        List<String> targetIdList = (List)param.get("targetIdList");
        return userCollectionMapper.deleteGoodsCollection(userId,targetIdList);

    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public HashMap<String,Object> getNineGoods() {
        HashMap<String,Object> map = new HashMap<>();
        Goods goods = goodsMapper.getLimitDiscount();
        List<Goods> goodsList = goodsMapper.getEightRecommend();
        map.put("first",goods);
        map.put("second",goodsList);
        return  map;
    }
}
